package com.dbpediamobile;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

//realiza la conexion a internet para obtener los datos de los nodos del grafo
public class GrafoConexion {
	String input;
	int offset, limit;
	public GrafoConexion(String input, int offset, int limit){
		this.input=input;
		this.offset= offset;
		this.limit=limit;
	}
	public String Conectar() throws IOException{
		String query = "++++select+%0D%0A%09%09++%09%28%3Csql%3As_sum_page%3E+%28%3Csql%3Avector_agg%3E+%28%3Cbif%3Avector%3E+%28%3Fc1%2C+%3Fsm%29%29%2C+%3Cbif%3Avector%3E+%28%27"+input+"%27%29%29%29++as+%3Fres+where+%7B+%7B+%0D%0A++++++select+%28%3CSHORT_OR_LONG%3A%3A%3E%28%3Fs1%29%29+as+%3Fc1%2C++%28%3Csql%3AS_SUM%3E+%28+%3CSHORT_OR_LONG%3A%3AIRI_RANK%3E+%28%3Fs1%29%2C+%3CSHORT_OR_LONG%3A%3A%3E%28%3Fs1textp%29%2C+%3CSHORT_OR_LONG%3A%3A%3E%28%3Fo1%29%2C+%3Fsc+%29+%29+as+%3Fsm++where+%7B+%3Fs1+%3Fs1textp+%3Fo1+.+%3Fo1+bif%3Acontains++%27%22"+input+"%22%27++option+%28score+%3Fsc%29++.+%7Dorder+by+desc+%28%3Csql%3Asum_rank%3E+%28%28%3Csql%3AS_SUM%3E+%28+%3CSHORT_OR_LONG%3A%3AIRI_RANK%3E+%28%3Fs1%29%2C+%3CSHORT_OR_LONG%3A%3A%3E%28%3Fs1textp%29%2C+%3CSHORT_OR_LONG%3A%3A%3E%28%3Fo1%29%2C+%3Fsc+%29+%29+%29+%29+limit+"+limit+"++offset+"+offset+"+%7D%7D&format=text%2Fhtml&debug=off&rt=Run+Query";
		
		String u = "http://dbpedia.org/sparql?default-graph-uri=http://dbpedia.org&should-sponge=&query="+query+"&format=XML&debug=off&timeout=";
		URL dir = new URL(u);
        URLConnection yc = dir.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        String salida="";
        
        while ((inputLine = in.readLine()) != null){
        	salida += inputLine;	
        }
        in.close();
		//return salida;
        return Document2String(this.string2Document(salida));
	}
	public Document string2Document(String s){ 
		Document tmpX=null; 
	    DocumentBuilder builder = null; 
	    int coderror;
		String msgerror;
		try{ 
	        builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
	    }catch(javax.xml.parsers.ParserConfigurationException error){ 
	        coderror=10; 
	        msgerror="Error crando factory String2DOM "+error.getMessage(); 
	        return null; 
	    } 
	    try{ 
	        tmpX=builder.parse(new ByteArrayInputStream(s.getBytes())); 
	    }catch(org.xml.sax.SAXException error){ 
	        coderror=10; 
	        msgerror="Error parseo SAX String2DOM "+error.getMessage(); 
	        return null; 
	    }catch(IOException error){ 
	        coderror=10; 
	        msgerror="Error generando Bytes String2DOM "+error.getMessage(); 
	        return null; 
	    } 
	    return tmpX; 
	} 
	
	private String Document2String(Document doc){
		
		NodeList listOfPersons = doc.getElementsByTagName("row");
		int totalPersons = listOfPersons.getLength();
		String nodos = "";
		for(int s=0; s<listOfPersons.getLength() ; s++){

			Node firstPersonNode = listOfPersons.item(s);
			if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
				
				Element firstPersonElement = (Element)firstPersonNode; 
				
				NodeList firstNameList = firstPersonElement.getElementsByTagName("column");
				Element firstNameElement = (Element)firstNameList.item(3);
		
				NodeList textFNList = firstNameElement.getChildNodes();
				nodos += ((Node)textFNList.item(0)).getNodeValue()+"*";
		
			}
		}
		return nodos;
	}
}
